package com.wash.shoes.domain.dy.util;

import com.google.gson.FieldNamingPolicy;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import okhttp3.*;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

public class HttpUtil {
    public static <T> T HttpPost(String uri, String bodyStr, String protocol, String domain, Class<T> classOfT) throws IOException {
        System.out.println(bodyStr);
        Gson gson = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE).create();
        OkHttpClient client = new OkHttpClient().newBuilder()
            .build();
        MediaType mediaType = MediaType.parse("application/json");
        RequestBody body = RequestBody.create(
                mediaType,
                bodyStr);
        String path =  protocol + "://" + domain + uri;
        System.out.println(path);
        Request request1 = new Request.Builder()
                .url(path)
                .method("POST", body)
                .addHeader("Content-Type", "application/json")
                .build();

        Response response = client.newCall(request1).execute();

        if (response.code() != 200) {
            return null;
        }
        ResponseBody responseBody = response.body();
        if (responseBody != null) {
            byte[] bodyByte = responseBody.bytes();

            if (bodyByte != null && bodyByte.length != 0) {
                String bodyString = new String(bodyByte, StandardCharsets.UTF_8);

                System.out.println(bodyString);
                return gson.fromJson(bodyString, classOfT);
            }
        }
        return null;
    }

}
